/* eslint-disable no-unused-vars */
/* eslint-disable eqeqeq */
/* eslint-disable no-param-reassign */
/* eslint-disable array-callback-return */
import React from 'react';
import _ from 'lodash';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Select,
  message,
  Steps,
  Divider,
  Spin,
  InputNumber,
  Checkbox,
  Input,
  Radio,
} from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import { urlParse } from '@/utils/utils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import Area from '../../components/Area';

const { Option } = Select;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Step } = Steps;
const CheckboxGroup = Checkbox.Group;

@connect(({ quoupdate, loading }) => ({
  loading: loading.models.quoupdate,
  productData: quoupdate.productData, // 产品列表
  updateDetailData: quoupdate.updateDetailData, // 修改前查看
  nextData: quoupdate.nextData,
  quoupdate,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dictData: { PAY_FEES_WAY: [], BIZ_INS_TYPE: [], ISNULL_FLAG: [], PRODUCT_WAGE_TYPE: [] },
      pdList: [], // 产品ID
      packList: [], // 包的数组
      matchList: [], // 包组合查询产品地区建议售价
      taxRatio: '', // 税率
      getListAll: [],
      serType: '',
      detailPackList: [],
      quoId: '',
      quoState: '',
      subData: {},

      allProductList: [],
    };
  }

  componentDidMount() {
    const getList = JSON.parse(window.localStorage.getItem('quotationadd'));
    const { dispatch, location, quoupdate, nextData, updateDetailData } = this.props;
    const { pdList } = this.state;
    const { quoId, quoState, preInfo } = urlParse(location.search);
    // 获取页面所需字典
    this.setState({
      getListAll: JSON.stringify(nextData) == '{}' ? getList : nextData,
      packList: JSON.stringify(nextData) == '{}' ? getList.packList : nextData.packList,
      detailPackList:
        JSON.stringify(nextData) == '{}' ? getList.detailPackList : nextData.detailPackList,
      taxRatio: JSON.stringify(nextData) == '{}' ? getList.taxRatio : nextData.taxRatio,
      serType: JSON.stringify(nextData) == '{}' ? getList.serType : nextData.serType,
      pdList: JSON.stringify(nextData) == '{}' ? getList.pdId : nextData.pdId,
      quoId,
      quoState,
      allProductList: getList.allProductList || [],
    });
    if (!preInfo) {
      dispatch({
        type: 'quoupdate/updateModelData',
        payload: { nextSubmitData: {} },
      });
      dispatch({
        type: 'publicdata/fetchDictCode',
        payload: ['PAY_FEES_WAY', 'BIZ_INS_TYPE', 'ISNULL_FLAG', 'PRODUCT_WAGE_TYPE'],
      }).then(data => {
        this.setState({ dictData: data }, () => {
          this.getProductAttr(pdList);
        });
      });
    } else {
      dispatch({
        type: 'publicdata/fetchDictCode',
        payload: ['PAY_FEES_WAY', 'BIZ_INS_TYPE', 'ISNULL_FLAG', 'PRODUCT_WAGE_TYPE'],
      }).then(data => {
        this.setState({ dictData: data }, () => {
          // eslint-disable-next-line no-unused-expressions
          JSON.stringify(nextData) == '{}' ? this.getProductAttr(pdList) : this.getProduct(pdList);
        });
      });
      this.setState({
        packList: JSON.stringify(nextData) == '{}' ? getList.packList : nextData.packList,
      });
    }
  }

  // 获取产品属性
  getProduct = pdIds => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/getAccess',
      payload: pdIds,
      callback: res => {
        if (res.success) {
          const newReaData = res.data;
          const { packList, detailPackList, taxRatio, allProductList } = this.state;
          res.data = _.unionBy([...newReaData, ...allProductList], 'pdId');
          packList.map((pack, index) => {
            if (pack.listQuoPd.length) {
              pack.listQuoPd.map(pd => {
                pd.listInfo = [];

                res.data.map(item => {
                  if (pd.pdId == item.pdId) {
                    pd.pdName = item.pdName;
                    pd.summary = item.summContent;
                    pd.pdAttrVOs = item.pdAttrVOs;
                    pd.pdCate = item.pdCate;
                  }
                });
              });
            }
            pack.listQuoPd.map((qunitem, cheindex) => {
              // eslint-disable-next-line no-unused-expressions
              qunitem.listAttr &&
                qunitem.listAttr.map((liqitem, liqindex) => {
                  qunitem.pdAttrVOs.map(cheitem => {
                    qunitem.listAttrPrice.map((lalitem, iindex) => {
                      if (lalitem.attrId == cheitem.attrId) {
                        cheitem.checked = [];
                        cheitem.checked = lalitem.attrVal.split(',');
                      }
                    });
                  });
                });
            });
          });
          if (taxRatio) {
            packList.map(moitem => {
              moitem.priceList.map(pricitem => {
                const { serType } = this.state;
                if (!serType) {
                  message.warning('请先确定合同的服务类型，否则没法计算税率');
                  return;
                }
                pricitem.taxMoney = pricitem.taxMoney;
              });
            });
          }
          this.setState({ packList });
        } else {
          message.warning(`获取产品属性数据失败!`);
        }
      },
    });
  };

  // 获取产品属性
  getProductAttr = pdIds => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/getAccess',
      payload: pdIds,
      callback: res => {
        if (res.success) {
          const newReaData = res.data;
          const { packList, detailPackList, taxRatio, allProductList } = this.state;
          res.data = _.unionBy([...newReaData, ...allProductList], 'pdId');
          packList.map((pack, index) => {
            // 如果是修改的新增
            if (!pack.priceList) {
              pack.priceList = [
                {
                  id: pack.index,
                  areaId: [], // 执行地区
                  suggPrice: '0', //	建议售价
                  quotePrice: '0.00', // 报价金额
                  taxMoney: '', // 税金
                },
              ];
            }
            if (pack.listQuoPd.length) {
              pack.listQuoPd.map(pd => {
                pd.listInfo = [];

                res.data.map(item => {
                  if (pd.pdId == item.pdId) {
                    pd.pdName = item.pdName;
                    pd.summary = item.summContent;
                    pd.pdAttrVOs = item.pdAttrVOs;
                    pd.pdCate = item.pdCate;
                  }
                });
              });
            }

            pack.listIndex = 0;
            detailPackList.map(priceitem => {
              priceitem.priceList.map((plitem, plindex) => {
                if (plitem.areaId == '') {
                  plitem.id = plindex;
                  plitem.areaIdList = [];
                  plitem.areaNameList = [];
                  plitem.areaList = [];
                } else {
                  plitem.id = plindex;
                  plitem.areaIdList = plitem.areaId.split(',');
                  plitem.areaNameList = plitem.areaName.split(',');
                  plitem.areaList = [];
                  plitem.areaIdList.map((areaitem, areaindex) => {
                    const newAreaIdObj = {};
                    newAreaIdObj.key = areaitem;
                    plitem.areaList[areaindex] = newAreaIdObj;
                  });
                  plitem.areaNameList.map((areanameitem, areanameindex) => {
                    plitem.areaList[areanameindex].label = areanameitem;
                  });
                }
              });
              pack.listQuoPd.map((citem, cindex) => {
                priceitem.listQuoPd.map((cityitem, cityindex) => {
                  if (cityitem.pdId == citem.pdId) {
                    pack.priceList = priceitem.priceList;
                  }
                });
              });
            });
          });
          newReaData.map(newitem => {
            if (newitem.pdAttrVOs) {
              newitem.pdAttrVOs.map(items => {
                detailPackList.map(detailitem => {
                  detailitem.listQuoPd.map(itemquo => {
                    itemquo.listAttr.map(itemattr => {
                      if (itemattr.attrId == items.attrId) {
                        items.checked = itemattr.attrValList;
                      }
                    });
                  });
                });
              });
            }
          });
          const newResdata = [];
          const pdsMessage = {};
          res.data.map(itemre => {
            packList.map((litem, lindex) => {
              if (itemre.pdAttrVOs) {
                itemre.pdAttrVOs.map((itemss, index) => {
                  pdsMessage.index = index;
                  pdsMessage.lindex = lindex;
                  pdsMessage.pdId = itemre.pdId;
                  this.attrChange(lindex, itemre.pdId, index); // 第几个包，产品ID，属性的下标
                });
              }
            });
            newResdata.push(pdsMessage);
          });

          if (taxRatio) {
            packList.map(moitem => {
              moitem.priceList.map(pricitem => {
                const { serType } = this.state;
                if (!serType) {
                  message.warning('请先确定合同的服务类型，否则没法计算税率');
                  return;
                }
                pricitem.taxMoney = pricitem.taxMoney;
              });
            });
          }
          this.setState({ packList });
        } else {
          message.warning(`获取产品属性数据失败!`);
        }
      },
    });
  };

  // 地区模糊搜索
  getData = (value, id, packIndex, numberId) => {
    const { matchList } = this.state;
    const newValue = [];
    value.map(item => {
      newValue.push(item.key);
    });

    if (id) {
      this.setState({ [id]: newValue });
    }
    const { packList } = this.state;
    packList[packIndex].priceList.map(item => {
      if (item.id == numberId) {
        item.areaId = newValue;
        item.areaList = value;
        item.areaIdList = newValue;
      }
    });
    this.setState({ packList }, () => {
      this.getMatchNew(newValue, matchList, packIndex, numberId);
    });
  };

  getMatchNew = (areaId, matchLists, packIndex) => {
    const { packList } = this.state;
    const { dispatch } = this.props;
    const matchList = [];
    packList[packIndex].listQuoPd.map(item => {
      if (item.pdAttrVOs && item.listAttrPrice) {
        matchList.push({
          pdId: item.pdId,
          pdSpecifAttr: item.listAttrPrice,
        });
      } else {
        matchList.push({
          pdId: item.pdId,
          pdSpecifAttr: [],
        });
      }
    });

    dispatch({
      type: 'quoupdate/getMatch',
      payload: { areaId: areaId && areaId.length > 1 ? [] : areaId, matchList },
      callback: res => {
        if (res.success) {
          let sum = 0;
          res.data.map(itm => {
            sum += itm.suggPrice;
            packList[packIndex].listQuoPd.map(item => {
              if (itm.pdId == item.pdId) {
                if (areaId) {
                  item.listInfo.push({
                    areaId,
                    suggPrice: itm.suggPrice,
                  });
                }
              }
            });
          });
          packList[packIndex].priceList.map(item => {
            item.suggPrice = sum;
          });
          this.setState({ packList });
        } else {
          message.warning(`获取失败!`);
        }
      },
    });
  };

  // 城市 - 减少
  unCheck = (value, id, packIndex, numberId) => {
    // packIndex第几个包,第几个地区
    const { packList, matchList } = this.state;
    packList[packIndex].priceList.map(item => {
      if (item.id == numberId) {
        const newAreaId = [];
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < item.areaId.length; i++) {
          if (item.areaId[i] != value.key) {
            newAreaId.push(item.areaId[i]);
          } else {
            return;
          }
        }
        item.areaId = newAreaId;
      }
    });
    this.setState({ packList }, () => {
      this.reducePrice(value.key, matchList, packIndex, numberId);
    });
  };

  // 建议售价 - 减少
  reducePrice = (areaId, matchLists, packIndex, numberId) => {
    const { dispatch } = this.props;
    const { packList } = this.state;
    const matchList = [];
    packList[packIndex].listQuoPd.map(item => {
      if (item.pdAttrVOs && item.listAttrPrice) {
        matchList.push({
          pdId: item.pdId,
          pdSpecifAttr: item.listAttrPrice,
        });
      } else {
        matchList.push({
          pdId: item.pdId,
          pdSpecifAttr: [],
        });
      }
    });

    dispatch({
      type: 'quoupdate/getMatch',
      payload: { areaId, matchList },
      callback: res => {
        if (res.success) {
          let sum = 0;
          res.data.map(itm => {
            sum += itm.suggPrice;
            packList[packIndex].listQuoPd.map(item => {
              if (itm.pdId == item.pdId) {
                if (areaId) {
                  const newAreaId = [];
                  item.listInfo.map(aritem => {
                    if (aritem.areaId !== areaId) {
                      newAreaId.push({ areaId: aritem.areaId, suggPrice: aritem.suggPrice });
                    }
                  });

                  item.areaId = newAreaId;
                }
              }
            });
          });
          packList[packIndex].priceList.map(item => {
            if (item.id == numberId) {
              if (item.suggPrice) {
                // eslint-disable-next-line radix
                item.suggPrice = parseInt(item.suggPrice) - sum;
              } else {
                item.suggPrice = sum;
              }
            }
          });

          packList.map(it => {
            it.listQuoPd.map(itemq => {
              const newAreaIds = [];
              itemq.listInfo.map(arqitem => {
                if (arqitem.areaId !== areaId) {
                  newAreaIds.push({ areaId: arqitem.areaId, suggPrice: arqitem.suggPrice });
                }
                arqitem = newAreaIds;
              });
            });
          });
          this.setState({ packList });
        } else {
          message.warning(`获取失败!`);
        }
      },
    });
  };

  // 上一步
  goBack = () => {
    const { quoId, quoState } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: {
        isGoBack: true,
      },
    });
    router.push(`/SaleManage/quotation/update?quoId=${quoId}&quoState=${quoState}`);
  };

  // 属性选择
  attrChange = (packIndex, pdId, attrIndex) => {
    const { packList, matchList } = this.state;
    const { form } = this.props;
    setTimeout(() => {
      let pdSpecifAttr = [];
      let pdSpecifAttrs = [];
      packList[packIndex].listQuoPd.map(quoitem => {
        if (quoitem.pdId == pdId) {
          quoitem.aleadyAttr = quoitem.aleadyAttr || [];
          if (quoitem.pdAttrVOs) {
            quoitem.pdAttrVOs.map((attr, index) => {
              const submitObj = {};
              submitObj.attrId = attr.attrId;
              submitObj.dictType = attr.dictType;
              submitObj.attrName = attr.attrName;
              const obj = {};
              obj.attrId = attr.attrId;
              if (index == attrIndex) {
                quoitem.aleadyAttr[attrIndex] = form.getFieldValue(
                  `pdAttr_${attr.attrId}_${packIndex}`
                );
                submitObj.attrValList =
                  (quoitem.aleadyAttr &&
                    quoitem.aleadyAttr[attrIndex] &&
                    quoitem.aleadyAttr[attrIndex].join(',')) ||
                  [];
                obj.attrVal =
                  (quoitem.aleadyAttr &&
                    quoitem.aleadyAttr[attrIndex] &&
                    quoitem.aleadyAttr[attrIndex].join(',')) ||
                  [];
              } else {
                quoitem.aleadyAttr[attrIndex] = form.getFieldValue(
                  `pdAttr_${attr.attrId}_${packIndex}`
                );
                submitObj.attrValList =
                  (quoitem.aleadyAttr &&
                    quoitem.aleadyAttr[attrIndex] &&
                    quoitem.aleadyAttr[attrIndex].join(',')) ||
                  [];
                obj.attrVal =
                  (quoitem.aleadyAttr &&
                    quoitem.aleadyAttr[attrIndex] &&
                    quoitem.aleadyAttr[attrIndex].join(',')) ||
                  [];
              }
              pdSpecifAttr.push(submitObj);
              pdSpecifAttrs.push(obj);
            });
          } else {
            pdSpecifAttr = [];
            pdSpecifAttrs = [];
          }
          quoitem.listAttr = pdSpecifAttr; // 提交数据用
          quoitem.listAttrPrice = pdSpecifAttrs; // 查建议售价
        }
      });

      this.setState({ packList }, () => {
        // eslint-disable-next-line no-unused-expressions
        packList[packIndex] &&
          packList[packIndex].priceList &&
          packList[packIndex].priceList.map(item => {
            this.getMatchNew(item.areaIdList, matchList, packIndex, item.id);
          });
      });
    }, 0);
  };

  // 通过报价金额获取税金
  numberChange = (value, packIndex, numberId) => {
    const { form } = this.props;
    const { packList, taxRatio } = this.state;
    // packList[packIndex].priceList[numberId].quotePrice = value;

    packList[packIndex].priceList.map(item => {
      if (item.id === numberId) {
        item.quotePrice = value;
        item.taxMoney = this.getTaxRate(value, taxRatio);
      }
    });

    if (value) {
      const priceSum = this.getTaxRate(value, taxRatio);
      const getFieldsList = form.getFieldsValue();

      // eslint-disable-next-line no-restricted-syntax
      for (const key in getFieldsList) {
        if (key == `taxMoney_${numberId}_${packIndex}`) {
          form.setFieldsValue({ [key]: priceSum });
        }
      }
    } else {
      const getFieldsList = form.getFieldsValue();
      // eslint-disable-next-line no-restricted-syntax
      for (const key in getFieldsList) {
        if (key == `taxMoney_${numberId}_${packIndex}`) {
          form.resetFields([key]);
        }
      }
    }
  };

  // 添加地区
  addList = packIndex => {
    const { packList } = this.state;
    const newData = packList;
    newData[packIndex].priceList.push({
      id: new Date().getTime(),
      areaId: [], // 执行地区
      suggPrice: '', //	建议金额
      quotePrice: '0.00', // 报价金额
      taxMoney: '', // 税金
    });
    this.setState({ packList: newData });
  };

  // 删除地区
  delList = (packIndex, id) => {
    const { packList } = this.state;
    const newData = packList;
    const priceList = packList[packIndex].priceList.filter(item => item.id !== id);
    newData[packIndex].priceList = priceList;
    this.setState({ packList: newData });
  };

  // 计算税率
  getTaxRate = (price, taxR) => {
    // 输入的，税率
    const { serType } = this.state;
    if (!serType) {
      message.warning('请先确定合同的服务类型，否则没法计算税率');
      return;
    }
    const taxRate = Math.round(price * (taxR / 100) * 100) / 100;
    // eslint-disable-next-line consistent-return
    return taxRate;
  };

  // 下一步：提交数据
  sumSubmit = () => {
    const { getListAll, packList, quoId, quoState } = this.state;
    const { form, dispatch, nextData } = this.props;
    const submitPackList = JSON.parse(JSON.stringify(packList));
    form.validateFieldsAndScroll(err => {
      if (!err) {
        submitPackList.map(item => {
          item.listQuoPd.map(pd => {
            pd.listArear = [];
            if (quoState == 1) {
              delete pd.pdAttrVOs;
              delete pd.listAttrPrice;
            }
            item.priceList.map(it => {
              it.areaIds = it.areaIdList;
              pd.listInfo.map(newitem => {
                pd.listArear.push(newitem);
              });
            });
          });
        });
        if (quoState == 1) {
          submitPackList.map(lastitem => {
            lastitem.priceList.map(itemsl => {
              delete itemsl.areaId;
            });
          });
        }
        submitPackList.map(lastitem => {
          lastitem.priceList.map(itemsl => {
            itemsl.areaId = itemsl.areaIds;
          });
        });
        submitPackList.map(lastitem => {
          if (quoState == 1) {
            lastitem.priceList.map(itemsl => {
              delete itemsl.areaIds;
            });
          }
          lastitem.listQuoPd.map(quoitem => {
            quoitem.newListArear = [];
            quoitem.listArear.map(aritem => {
              if (typeof aritem.areaId != 'object') {
                quoitem.newListArear.push(aritem);
              }
            });
            quoitem.newlistInfo = [];
            quoitem.listInfo.map(qulitem => {
              if (typeof qulitem.areaId != 'object') {
                quoitem.newlistInfo.push(qulitem);
              }
            });
            quoitem.listArear = quoitem.newListArear;
            quoitem.listInfo = quoitem.newlistInfo;
          });
        });
        if (quoState == '1') {
          submitPackList.map(lastitem => {
            lastitem.listQuoPd.map(itemsql => {
              delete itemsql.newListArear;
              delete itemsql.newlistInfo;
            });
          });
        }
        const submitData = {
          suppId: getListAll.suppId,
          custId: getListAll.custId,
          custContId: getListAll.custContId,
          serType: getListAll.serType,
          taxFlag: getListAll.taxFlag,
          taxRatio: getListAll.taxFlag === '2' ? getListAll.taxRatio : null,
          quoName: getListAll.quoName,
          quoType: getListAll.quoType,
          packList: submitPackList,
          quoId,
        };

        submitData.packList.map(lsitem => {
          lsitem.allAreaId = [];
          lsitem.priceList.map(lspitem => {
            if (getListAll.taxFlag === '1') {
              lspitem.taxMoney = null;
            }
            lspitem.areaId.map(lsaitem => {
              lsitem.allAreaId.push(lsaitem);
            });
          });
        });
        let flag = 1;
        submitData.packList.map(slitem => {
          if (new Set(slitem.allAreaId).size !== slitem.allAreaId.length) {
            if (flag === 1) {
              message.warning('同一包下不可存在相同地区');
              flag = 2;
            } else {
              flag = 1;
            }
          }
        });
        if (flag === 1) {
          if (quoState == '1') {
            submitData.packList.map(packitem => {
              delete packitem.listIndex;
              delete packitem.allAreaId;
              packitem.listQuoPd.map(quoPditem => {
                delete quoPditem.listInfo;
                delete quoPditem.listArear;
                delete quoPditem.aleadyAttr;
              });
              packitem.priceList.map(pritem => {
                delete pritem.areaIdList;
                delete pritem.areaList;
                delete pritem.areaNameList;
                delete pritem.id;
                delete pritem.areaName;
                pritem.areaId = pritem.areaId.join(',');
                if (pritem.dicTaxFlag) {
                  delete pritem.dicTaxFlag;
                }
              });
            });

            dispatch({
              type: 'quoupdate/updateSubmit',
              payload: submitData,
              callback: subres => {
                if (subres.success) {
                  router.push(
                    `/salemanage/quotation/updatefinished?quoId=${
                      submitData.quoId
                    }&quoState=${quoState}`
                  );
                } else {
                  message.warning(subres.message || '服务端未知错误');
                }
              },
            });
          } else {
            dispatch({
              type: 'quoupdate/updateModelData',
              payload: { nextData: submitData, nextFinishData: submitData },
            });
            this.setState({ subData: submitData }, () => {
              const { subData } = this.state;
              dispatch({
                // 有没有人员
                type: 'quoupdate/isHavaEmp',
                payload: { custId: subData.custId, quoId: subData.quoId },
              }).then(res => {
                if (res.success) {
                  // 有人员的话下一步
                  if (res.data.sendCount > 0) {
                    subData.packList.map(packitem => {
                      packitem.priceList.map(pritem => {
                        pritem.areaId = pritem.areaId.join(',');
                        if (pritem.dicTaxFlag) {
                          delete pritem.dicTaxFlag;
                        }
                      });
                    });
                    dispatch({
                      type: 'quoupdate/nextPeopleInfo',
                      payload: subData,
                    }).then(resc => {
                      if (resc.success) {
                        let btn = 2;
                        // eslint-disable-next-line no-unused-expressions
                        resc.data &&
                          resc.data.responseQuoDtos &&
                          resc.data.responseQuoDtos.map(ishItem => {
                            if (ishItem.oldQuo.hasPro === false) {
                              btn = 1;
                            }
                            if (ishItem.newQuo.hasPro === false) {
                              btn = 1;
                            }
                          });
                        router.push(
                          `/salemanage/quotation/personnelinfo?quoId=${quoId}&quoState=${quoState}&batchNumber=${
                            resc.data.cacheKey
                          }&btn=${btn}`
                        );
                      }
                    });
                  } else {
                    // 没有人员的话直接修改提交

                    submitData.packList.map(packitem => {
                      delete packitem.listIndex;
                      delete packitem.allAreaId;
                      packitem.listQuoPd.map(quoPditem => {
                        delete quoPditem.listInfo;
                        delete quoPditem.listArear;
                        delete quoPditem.aleadyAttr;
                      });
                      packitem.priceList.map(pritem => {
                        delete pritem.areaIdList;
                        delete pritem.areaList;
                        delete pritem.areaNameList;
                        delete pritem.id;
                        delete pritem.areaName;
                        pritem.areaId = pritem.areaId.join(',');
                        if (pritem.dicTaxFlag) {
                          delete pritem.dicTaxFlag;
                        }
                      });
                    });

                    dispatch({
                      type: 'quoupdate/updateSubmit',
                      payload: submitData,
                      callback: info => {
                        if (info.success) {
                          router.push(
                            `/salemanage/quotation/updatefinished?quoId=${
                              submitData.quoId
                            }&quoState=3`
                          );
                        } else {
                          message.warning(info.message || '服务端未知错误');
                        }
                      },
                    });
                  }
                } else {
                  message.warning(res.message || '服务端未知错误！');
                }
              });
            });
          }
        }
      }
    });
  };

  // 渲染函数
  render() {
    const { dictData, packList, taxRatio, quoState } = this.state;
    const { loading, form } = this.props;
    const { getFieldDecorator } = form;
    const sortNumber = (a, b) => b.itemCode - a.itemCode;

    // 产品属性（缴费方式|缴费险种）复选框内容展示
    const attrOptions = (dictType, ids) => {
      dictData[dictType] = dictData[dictType].sort(sortNumber);
      const arr = [];
      dictData[dictType].map(items => {
        items.disabled = ids && ids.indexOf(items.itemCode) > -1;
        const obj = {};
        obj.label = items.itemName;
        obj.value = items.itemCode;
        if (quoState === '2') {
          obj.disabled = items.disabled;
        }
        arr.push(obj);
      });
      return arr;
    };
    return (
      <Form>
        <PageHeaderWrapper>
          <Spin tip="Loading..." spinning={loading}>
            <Card>
              <Steps current={1} style={{ marginBottom: 70 }}>
                <Step title="选择产品" />
                <Step title="设置价格" />
                {quoState == 1 ? null : <Step title="人员信息" />}
                <Step title="完成" />
              </Steps>
              {packList &&
                packList.map((pack, packIndex) => (
                  // eslint-disable-next-line react/no-array-index-key
                  <Card style={{ marginBottom: 16, border: '1px solid #e8e8e8' }} key={packIndex}>
                    {// 产品
                    pack.listQuoPd &&
                      pack.listQuoPd.map((pd, index) => (
                        <div key={pd.pdId}>
                          {index ? <Divider dashed /> : null}
                          <FormItem
                            label="产品名称"
                            labelCol={{ span: 2 }}
                            style={{ marginBottom: 10 }}
                          >
                            {getFieldDecorator(`name_${pd.pdId}_${packIndex}`, {
                              rules: [{ required: false, message: '请选择' }],
                            })(<div>{pd.pdName}</div>)}
                          </FormItem>
                          {pd.pdAttrVOs &&
                            // eslint-disable-next-line no-shadow
                            pd.pdAttrVOs.map((attrList, index) => (
                              <FormItem
                                key={attrList.attrId}
                                label={attrList.attrName}
                                labelCol={{ span: 2 }}
                                wrapperCol={{ span: 10 }}
                                style={{ marginBottom: 10 }}
                              >
                                {getFieldDecorator(`pdAttr_${attrList.attrId}_${packIndex}`, {
                                  rules: [{ required: true, message: '请选择' }],
                                  initialValue: attrList.checked,
                                })(
                                  // eslint-disable-next-line no-nested-ternary
                                  attrList.inputType == '5' ? (
                                    <CheckboxGroup
                                      options={attrOptions(attrList.dictType, attrList.checked)}
                                      onChange={() => this.attrChange(packIndex, pd.pdId, index)}
                                    />
                                  ) : attrList.inputType == '4' ? (
                                    <Select
                                      placeholder="请选择"
                                      showSearch
                                      optionFilterProp="children"
                                      style={{ width: 250 }}
                                      onChange={e => this.attrChange(e, packIndex, attrList)}
                                    >
                                      {attrOptions(attrList.dictType).map(p => (
                                        // eslint-disable-next-line react/no-array-index-key
                                        <Option key={`pdAttrSelect_${index}`} value={p.value}>
                                          {p.label}
                                        </Option>
                                      ))}
                                    </Select>
                                  ) : (
                                    <RadioGroup
                                      style={{ marginLeft: 15 }}
                                      options={attrOptions(attrList.dictType)}
                                      onChange={() => this.attrChange(packIndex, pd.pdId, index)}
                                    />
                                  )
                                )}
                              </FormItem>
                            ))}
                        </div>
                      ))}
                    {pack.priceList && pack.priceList.length ? <Divider /> : null}
                    {// 定价
                    pack.priceList &&
                      pack.priceList.map((item, index) => (
                        <div key={item.id}>
                          {index ? <Divider dashed /> : null}
                          <div key={item.id}>
                            <FormItem
                              label="执行地区"
                              labelCol={{ span: 2 }}
                              wrapperCol={{ span: 10 }}
                              style={{ marginBottom: 20 }}
                            >
                              {getFieldDecorator(`areaId_${item.id}_${packIndex}`, {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: item.areaList,
                              })(
                                <Area
                                  labelInValue
                                  isContainNation
                                  onChange={value =>
                                    this.getData(
                                      value,
                                      `areaId_${item.id}_${packIndex}`,
                                      packIndex,
                                      item.id
                                    )
                                  }
                                  style={{ width: 220 }}
                                  mode="multiple"
                                />
                              )}
                              {pack.priceList.length > 1 ? (
                                <a
                                  style={{ marginLeft: 30 }}
                                  onClick={e => {
                                    e.preventDefault();
                                    this.delList(packIndex, item.id);
                                  }}
                                >
                                  删除
                                </a>
                              ) : null}
                            </FormItem>
                            <FormItem
                              label="报价金额"
                              labelCol={{ span: 2 }}
                              wrapperCol={{ span: 10 }}
                              style={{ marginBottom: 20 }}
                            >
                              {getFieldDecorator(`quotePrice_${item.id}_${packIndex}`, {
                                rules: [
                                  {
                                    required: true,
                                    message: '请输入小数点不超过2位的数字',
                                    pattern: /^-?\d+\.?\d{0,2}$/,
                                  },
                                ],
                                initialValue: item.quotePrice,
                              })(
                                <InputNumber
                                  min={0}
                                  max={9999999.99}
                                  placeholder="请输入"
                                  style={{ width: '100px' }}
                                  onChange={value => this.numberChange(value, packIndex, item.id)}
                                />
                              )}
                              <span>（建议售价：{item.suggPrice}）</span>
                            </FormItem>
                            {taxRatio == null ? null : (
                              <FormItem
                                label="税金"
                                labelCol={{ span: 2 }}
                                wrapperCol={{ span: 10 }}
                                style={{ marginBottom: 20 }}
                              >
                                {getFieldDecorator(`taxMoney_${item.id}_${packIndex}`, {
                                  rules: [{ required: false, message: '请选择' }],
                                  initialValue: item.taxMoney == 'NaN' ? null : item.taxMoney,
                                })(<Input style={{ width: '100px' }} disabled />)}
                                <span>（税率：{taxRatio}%）</span>
                              </FormItem>
                            )}
                          </div>
                        </div>
                      ))}
                    <FormItem
                      label="&nbsp;"
                      colon={false}
                      labelCol={{ span: 2 }}
                      wrapperCol={{ span: 10 }}
                    >
                      <Button
                        style={{ width: 220, textAlign: 'center' }}
                        type="dashed"
                        icon={<PlusOutlined />}
                        onClick={() => this.addList(packIndex)}
                      >
                        添加地区
                      </Button>
                    </FormItem>
                  </Card>
                ))}
              <div style={{ marginTop: 50, marginBottom: 30, textAlign: 'center' }}>
                <Button style={{ marginRight: 30 }} size="large" onClick={() => this.goBack()}>
                  上一步
                </Button>
                {quoState == 1 ? (
                  <Button type="primary" size="large" onClick={this.sumSubmit}>
                    提交
                  </Button>
                ) : (
                  <Button type="primary" size="large" onClick={this.sumSubmit}>
                    下一步
                  </Button>
                )}
              </div>
            </Card>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
